#include "jwt_util.h"
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "encode.h"
#include "decode.h"

#define JWT_SECRET_KEY "mySuperSecretKey_YouMustChangeThis"
#define JWT_SECRET_KEY_LEN (sizeof(JWT_SECRET_KEY) - 1)


// 生成JWT
int jwt_generate_token(const char *username, char *out_token, size_t out_token_size, int expire_seconds)
{
    if (!username || !out_token || out_token_size == 0) return -1;
    struct l8w8jwt_encoding_params params;
    l8w8jwt_encoding_params_init(&params);

    params.alg = L8W8JWT_ALG_HS512;
    params.sub = (char *)username;
    params.iss = (char *)JWT_ISSUER;
    params.aud = (char *)JWT_AUDIENCE;
    params.iat = l8w8jwt_time(NULL);
    params.exp = params.iat + expire_seconds;
    params.secret_key = (unsigned char *)JWT_SECRET_KEY;
    params.secret_key_length = JWT_SECRET_KEY_LEN;

    char *jwt = NULL;
    size_t jwt_len = 0;
    params.out = &jwt;
    params.out_length = &jwt_len;

    int r = l8w8jwt_encode(&params);
    if (r != L8W8JWT_SUCCESS || jwt == NULL) {
        if (jwt) l8w8jwt_free(jwt);
        return -1;
    }
    // 拷贝到输出
    if (jwt_len + 1 > out_token_size) {
        l8w8jwt_free(jwt);
        return -2; // 空间不足
    }
    strncpy(out_token, jwt, out_token_size - 1);
    out_token[out_token_size - 1] = '\0';
    l8w8jwt_free(jwt);
    return 0;
}

// 校验JWT
int jwt_verify_token(const char *token, const char *expected_username)
{
    if (!token || !expected_username) return -1;
    struct l8w8jwt_decoding_params params;
    l8w8jwt_decoding_params_init(&params);

    params.alg = L8W8JWT_ALG_HS512;
    params.jwt = (char *)token;
    params.jwt_length = strlen(token);
    params.verification_key = (unsigned char *)JWT_SECRET_KEY;
    params.verification_key_length = JWT_SECRET_KEY_LEN;
    params.validate_iss = (char *)JWT_ISSUER;
    params.validate_aud = (char *)JWT_AUDIENCE;
    params.validate_sub = (char *)expected_username; // 用户名校验
    params.validate_exp = 1; // 校验过期
    params.exp_tolerance_seconds = 60; // 60s宽容
    params.validate_iat = 1;
    params.iat_tolerance_seconds = 60;

    enum l8w8jwt_validation_result validation_result;
    int decode_result = l8w8jwt_decode(&params, &validation_result, NULL, NULL);

    if (decode_result == L8W8JWT_SUCCESS && validation_result == L8W8JWT_VALID) {
        return 0; // 有效
    }
    return -1; // 无效
}

